package cn.campsg.messageboard.controller;


import cn.campsg.messageboard.dao.MessageDaoImpl;
import cn.campsg.messageboard.idao.IMessageDao;
import cn.campsg.messageboard.model.Message;
import cn.campsg.messageboard.model.User;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import java.util.regex.Pattern;

@WebServlet(name = "MessageServlet", value = "/MessageServlet")
public class MessageServlet extends HttpServlet {
    private IMessageDao messageDao;

    @Override
    public void init() {
        messageDao = new MessageDaoImpl();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String action = request.getParameter("action");
        if (action == null) {
            action = "list";
        }

        try {
            switch (action) {
                case "search":
                    searchMessages(request, response);
                    break;
                case "reply":
                    showReplyPage(request, response);
                    break;
                case "edit":
                    showEditPage(request, response);
                    break;
                case "list":
                default:
                    listMessages(request, response);
                    break;
            }
        } catch (Exception e) {
            throw new ServletException(e);
        }
    }

    private void showEditPage(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        String msgIdStr = request.getParameter("msgId");
        if (msgIdStr == null) {
            response.sendRedirect("index.jsp");
            return;
        }
        int msgId = Integer.parseInt(msgIdStr);
        Message message = messageDao.getMessageById(msgId);
        request.setAttribute("message", message);
        request.getRequestDispatcher("message_edit.jsp").forward(request, response);
    }

    private void showReplyPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String msgIdStr = request.getParameter("msgId");
        if (msgIdStr == null) {
            response.sendRedirect("index.jsp");
            return;
        }
        int msgId = Integer.parseInt(msgIdStr);
        Message parentMsg = messageDao.getMessageById(msgId);
        request.setAttribute("parentMsg", parentMsg);
        request.getRequestDispatcher("message_edit.jsp").forward(request, response);
    }



    private void searchMessages(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, SQLException {
        String keyword = request.getParameter("keyword");
        int page = 1;
        int recordsPerPage = 10;

        if (request.getParameter("page") != null) {
            page = Integer.parseInt(request.getParameter("page"));
        }

        // 获取原始数据（DAO已过滤无关键字的留言）
        List<Message> messageList = messageDao.searchMessages(keyword, (page-1)*recordsPerPage, recordsPerPage);

        // 关键字标红处理
        if (keyword != null && !keyword.trim().isEmpty()) {
            for (Message msg : messageList) {
                msg.setContent(highlightKeyword(msg.getContent(), keyword));
                // 回复内容标红
                if (msg.getReplies() != null) {
                    for (Message reply : msg.getReplies()) {
                        reply.setContent(highlightKeyword(reply.getContent(), keyword));
                    }
                }
            }
        }

        // 计算总数（只统计包含关键字的留言）
        int totalRecords = messageDao.getSearchCount(keyword);
        int totalPages = (int) Math.ceil(totalRecords * 1.0 / recordsPerPage);

        request.setAttribute("messageList", messageList);
        request.setAttribute("messageCount", totalRecords);
        request.setAttribute("totalPages", totalPages);
        request.setAttribute("currentPage", page);
        request.setAttribute("keyword", keyword);

        request.getRequestDispatcher("/index.jsp").forward(request, response);
    }

    // 高亮方法（不变）
    private String highlightKeyword(String text, String keyword) {
        if (text == null || keyword == null || keyword.isEmpty()) return text;
        return text.replaceAll("(?i)(" + Pattern.quote(keyword) + ")",
                "<span style='color:red;font-weight:bold;'>$1</span>");
    }

    private void listMessages(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, SQLException {
        int page = 1;
        int recordsPerPage = 10;

        if (request.getParameter("page") != null) {
            page = Integer.parseInt(request.getParameter("page"));
        }

        List<Message> messageList = messageDao.getAllMessages((page-1)*recordsPerPage, recordsPerPage);
        int totalRecords = messageDao.getTotalCount();
        int totalPages = (int) Math.ceil(totalRecords * 1.0 / recordsPerPage);

        request.setAttribute("messageList", messageList);
        request.setAttribute("messageCount", totalRecords);
        request.setAttribute("totalPages", totalPages);
        request.setAttribute("currentPage", page);


        //request.getRequestDispatcher("/message.jsp").forward(request, response);
        request.getRequestDispatcher("/index.jsp").forward(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 处理留言的添加、删除等其他操作
        String action = request.getParameter("action");

        if ("add".equals(action)) {
            String content = request.getParameter("content");
            // 这里需要获取当前登录用户ID，示例中使用固定值1
            int userId = 1;
            messageDao.addMessage(userId, content);
        } else if ("reply".equals(action)) {
            String content = request.getParameter("content");
            int parentId = Integer.parseInt(request.getParameter("parentId"));
            // 获取当前登录用户id
            int userId = ((User)request.getSession().getAttribute("user")).getId();
            // 存入数据库
            messageDao.addReply(userId, content, parentId);
        }else if ("delete".equals(action)) {
            int msgId = Integer.parseInt(request.getParameter("msgId"));
            messageDao.deleteMessage(msgId);
        }
        response.sendRedirect("MessageServlet");
    }
}